package com.example.unisys.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaseUtils {
    public static String polyToken = "https://hls.videocc.net/service/v1/token";

    public static boolean isNumeric(String s) {
        return s.matches("-?\\d+(\\.\\d+)?");
    }


    public static String getFailListMessage(ArrayList<String> fails){
        StringBuilder msg=new StringBuilder("失败列表如下");
        fails.forEach(s->{
            msg.append(s+"|");
        });
        return msg.toString();
    }




    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }

    public static String stringToAscii(String value) {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]).append(",");
            } else {
                sbu.append((int) chars[i]);
            }
        }
        return sbu.toString();
    }

    public static String getMD5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");//获取MD5实例
            md.update(plainText.getBytes());//此处传入要加密的byte类型值
            byte[] digest = md.digest();//此处得到的是md5加密后的byte类型值

            /*
               下边的运算就是自己添加的一些二次小加密，记住这个千万不能弄错乱，
                   否则在解密的时候，你会发现值不对的（举例：在注册的时候加密方式是一种，
                在我们登录的时候是不是还需要加密它的密码然后和数据库的进行比对，但是
            最后我们发现，明明密码对啊，就是打不到预期效果，这时候你就要想一下，你是否
             有改动前后的加密方式）
            */
            int i;
            StringBuilder sb = new StringBuilder();
            for (int offset = 0; offset < digest.length; offset++) {
                i = digest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    sb.append(0);
                sb.append(Integer.toHexString(i));//通过Integer.toHexString方法把值变为16进制
            }
            return sb.toString();//从下标0开始，length目的是截取多少长度的值
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String http_build_query(Map<String, String> array) {
        String reString = "";
        //遍历数组形成akey=avalue&bkey=bvalue&ckey=cvalue形式的的字符串
        Iterator it = array.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry) it.next();
            String key = entry.getKey();
            String value = entry.getValue();
            reString += key + "=" + value + "&";
        }
        System.out.println("reString is " + reString);
        reString = reString.substring(0, reString.length() - 1);
        //将得到的字符串进行处理得到目标格式的字符串
        try {
            reString = java.net.URLEncoder.encode(reString, "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        reString = reString.replace("%3D", "=").replace("%26", "&");
        return reString;
    }


    public final static String MD52(String s) {
        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < md.length; i++) {
                int val = ((int) md[i]) & 0xff;
                if (val < 16)
                    sb.append("0");
                sb.append(Integer.toHexString(val));

            }
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }
    public static String getMd5(String input)
    {
        try {

            // Static getInstance method is called with hashing MD5
            MessageDigest md = MessageDigest.getInstance("MD5");

            // digest() method is called to calculate message digest
            //  of an input digest() return array of byte
            byte[] messageDigest = md.digest(input.getBytes());

            // Convert byte array into signum representation
            BigInteger no = new BigInteger(1, messageDigest);

            // Convert message digest into hex value
            String hashtext = no.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        }

        // For specifying wrong message digest algorithms
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String concat(String[] list){
        StringBuilder sb = new StringBuilder();
        Arrays.asList(list).forEach(item->{
            sb.append("#"+item);
        });
        return sb.toString();
    }

//    public static void main(String[] args) {
///*
//        HashMap<String,String>  hs = new HashMap<>();
//        hs.put("code","19238");
//        hs.put("videoid","1718");
//        hs.put("sign","aydfbiadf");
//        String query =http_build_query(hs);
//        System.out.println(query);
//        */
//
//        HashMap<String, String> hs = new HashMap<>();
//        hs.put("userId", "d6001adfae");
//        hs.put("secretkey", "00X97pOUEx");
//        hs.put("videoId", "d6001adfaec2d7dcf223a5fc0337e96f_d");
//        hs.put("ts", String.valueOf(System.currentTimeMillis() * 1000L));
//        hs.put("viewerIp", "119.98.203.13");
//        hs.put("viewerId", "12345");
//        hs.put("viewerName", "testUser");
//        hs.put("extraParams", "HTML5");
//        String userId = hs.get("userId");
//        String secretkey = hs.get("secretkey");
//        String videoId = hs.get("videoId");
//        String ts = hs.get("ts");
//        String viewerIp = hs.get("viewerIp");
//        String viewerId = hs.get("viewerId");
//        String viewerName = hs.get("viewerName");
//        String extraParams = hs.get("extraParams");
//        String concat = "extraParams" + extraParams + "ts" + ts + "userId" + userId + "videoId" + videoId + "viewerId" + viewerId + "viewerIp" + viewerIp + "viewerName" + viewerName;
//        String plain = secretkey + concat + secretkey;
//        //String asciiplain=Tools.stringToAscii(plain);
//        String sign = BaseUtils.getMd5(plain).toUpperCase();
//        hs.put("sign", sign);
//        hs.remove("secretkey");
//        String query = BaseUtils.http_build_query(hs);
//        //query=query.substring(4,query.length());
//        System.out.println("query string is " + query);
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Content-Type", "application/x-www-form-urlencoded");
//
//        HttpEntity<String> formEntity = new HttpEntity<>(query, headers);
//        RestTemplate restTemplate = new RestTemplate();
//        String token = restTemplate.postForEntity(polyToken, formEntity, String.class).getBody();
//        System.out.println(token);
//
////        HttpEntity<HashMap<String, String>> request = new HttpEntity<>(hs, headers);
////        RestTemplate restTemplate = new RestTemplate();
////        ResponseEntity<String> response = restTemplate.postForEntity( polyToken, request , String.class );
////        System.out.println(response);
//
//    }


}
